﻿using System;
using MySql.Data.MySqlClient;

namespace MySqlManager.DatabaseBuilder
{
    /// <summary>
    /// Layer class over a MySqlCommand to create a new MySQL Database 
    /// </summary>
    public class MySqlDatabaseCreator
    {
        /// <summary>
        /// True if the creation will be executed in a thread of the ThreadPool
        /// </summary>
        public bool CreateAsync;

        /// <summary>
        /// Methods that will be invoked once the database creation finishes
        /// </summary>
        public event Action Completed;

        /// <summary>
        /// Gets or sets the name for the database
        /// </summary>
        public string DatabaseName { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="MySqlDatabaseCreator"/> class
        /// </summary>
        /// <param name="databaseName"></param>
        public MySqlDatabaseCreator(string databaseName)
        {
            this.DatabaseName = databaseName;
        }

        /// <summary>
        /// If no database exists with the specified database name, create it
        /// </summary>
        public void CreateIfNotExists()
        {
            if (this.CreateAsync)
            {
                Action creation = this.ExecuteQuery;
                creation.BeginInvoke((IAsyncResult result) =>
                {
                    if (this.Completed != null)
                    {
                        this.Completed.Invoke();
                    }
                },
                null);
            }
            else
            {
                this.ExecuteQuery();
                if (this.Completed != null)
                {
                    this.Completed.Invoke();
                }
            }
        }

        /// <summary>
        /// Creates and execute the query that will create the database
        /// </summary>
        private void ExecuteQuery()
        {
            using (MySqlConnection connection = MySqlCore.GetConnection())
            {
                using (MySqlCommand cmd = new MySqlCommand("CREATE DATABASE IF NOT EXISTS " + this.DatabaseName, connection))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}
